"""
群成员扫描插件
功能：扫描当前群聊的所有成员，将 QQ 号与当前群名片写入共享数据库表 `user_nickname`
规则：如果该 QQ 号已存在（唯一键冲突），跳过，不修改已有记录

现在使用 Django Model 来管理数据库操作
"""
from typing import List, Tuple

from nonebot import on_command
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent
from nonebot.exception import FinishedException

# 使用 Django Model 替代直接 SQL 操作
from src.common.django_db import batch_create_user_nicknames


# 命令：扫描群成员
scan_group_members = on_command("扫描群成员", priority=5)


async def _batch_insert_user_nickname(rows: List[Tuple[int, str]]) -> int:
    """
    批量插入到 user_nickname 表，已存在则跳过（不更新）。返回插入条数。
    
    现在使用 Django Model 的 bulk_create 方法，更简洁和安全
    """
    if not rows:
        return 0

    # 使用 Django Model 批量创建
    # bulk_create 的 ignore_conflicts=True 参数等同于 INSERT IGNORE
    inserted = await batch_create_user_nicknames(rows)
    return inserted


@scan_group_members.handle()
async def handle_scan(bot: Bot, event: GroupMessageEvent):
    try:
        group_id = event.group_id

        # 获取群成员列表，尽量刷新缓存
        try:
            members = await bot.get_group_member_list(group_id=group_id, no_cache=True)
        except TypeError:
            members = await bot.get_group_member_list(group_id=group_id)

        if not members:
            await scan_group_members.finish("无法获取群成员列表")
            return

        # 组装插入数据：优先 card，其次 nickname；若两者皆空则跳过
        to_insert: List[Tuple[int, str]] = []
        skipped_empty = 0
        for m in members:
            qq = m.get("user_id")
            card = m.get("card", "") or ""
            nickname = m.get("nickname", "") or ""
            display = card or nickname
            if not qq:
                continue
            if not display:
                skipped_empty += 1
                continue
            to_insert.append((int(qq), str(display)))

        if not to_insert:
            await scan_group_members.finish("没有可插入的数据（所有成员名片均为空）")
            return

        inserted = await _batch_insert_user_nickname(to_insert)
        total = len(to_insert)
        ignored = total - inserted

        msg = (
            f"扫描完成\n"
            f"群成员数：{len(members)}\n"
            f"准备写入：{total}\n"
            f"成功新增：{inserted}\n"
            f"已存在跳过：{ignored}\n"
            f"空名片跳过：{skipped_empty}"
        )
        await scan_group_members.finish(msg)

    except FinishedException:
        raise
    except Exception as e:
        import traceback
        traceback.print_exc()
        await scan_group_members.finish(f"扫描并入库时发生错误：{e}")


